package com.ttg.web.dao.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ttg.common.entities.BasePage;
import com.ttg.common.enums.IntervalTypeEnum;
import com.ttg.model.dto.CostGradingMerchExportDTO;
import com.ttg.model.po.MerchTradeMonthPO;
import com.ttg.model.mapper.CostManageMerchTradeMonthMapper;
import com.ttg.model.pojo.CostManageMerchTradeMonth;
import com.ttg.web.dao.CostManageMerchTradeMonthDao;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * (TblCostManageMerchTradeMonth) daoImpl
 *
 * @author chenyou
 * @datetime 2025-10-16 11:10:06
 */
@Service
public class CostManageMerchTradeMonthDaoImpl extends ServiceImpl<CostManageMerchTradeMonthMapper, CostManageMerchTradeMonth> implements CostManageMerchTradeMonthDao {

    @Override
    public CostManageMerchTradeMonth getByUnique(Long mctNo,String intervalType, String year, String month, String lowerBound, String upperBound) {
        LambdaQueryWrapper<CostManageMerchTradeMonth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CostManageMerchTradeMonth::getMtmMctNo,mctNo);
        wrapper.eq(CostManageMerchTradeMonth::getMtmIntervalType,intervalType);
        if(IntervalTypeEnum.月度区间.getValue().equals(intervalType)){
            wrapper.eq(CostManageMerchTradeMonth::getMtmYear,year);
            wrapper.eq(CostManageMerchTradeMonth::getMtmMonth,month);

        }else if(IntervalTypeEnum.累计区间.getValue().equals(intervalType)){
            wrapper.eq(CostManageMerchTradeMonth::getMtmYear,year);
            wrapper.eq(CostManageMerchTradeMonth::getMtmLowerBound,lowerBound);
            wrapper.eq(CostManageMerchTradeMonth::getMtmUpperBound,upperBound);
        }
        return getOne(wrapper);
    }

    @Override
    public void saveOrUpdateBatch(List<CostManageMerchTradeMonth> list) {
        for(CostManageMerchTradeMonth body:list){
            CostManageMerchTradeMonth old = getByUnique(body.getMtmMctNo(),body.getMtmIntervalType(),body.getMtmYear(),body.getMtmMonth(),body.getMtmLowerBound(),body.getMtmUpperBound());
            if(Objects.isNull(old)){
                body.setMtmAddTime(LocalDateTime.now());
                body.setMtmUpdateTime(LocalDateTime.now());
                save(body);
            }else{
                body.setMtmId(old.getMtmId());
                body.setMtmUpdateTime(LocalDateTime.now());
                updateById(body);
            }
        }
    }

    @Override
    public List<CostManageMerchTradeMonth> getParam(MerchTradeMonthPO po) {
        return baseMapper.getParam(po);
    }

    @Override
    public BasePage<CostManageMerchTradeMonth> merchExport(BasePage page, MerchTradeMonthPO po) {
        return baseMapper.merchExport(page,po);
    }
}

